<template>
  <div class="left-bottom">
    <div class="header">
      <div class="chart-title">人口涌入与流失对比</div>
      <!-- 日期选择器 -->
      <!--  @change事件监听器 -->
      <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" @change="updateChart" />
    </div>
    <div ref="chart" class="chart-container"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      selectedDate: new Date(),
      chart: null,
      cities: ['北京', '上海', '广州', '深圳'],
      inflowData: [],
      outflowData: []
    };
  },
  mounted() {
    this.initChart();
    this.updateChart();
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['人口涌入', '人口流失'],
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: this.cities,
          axisLabel: {
            color: '#fff'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#fff'
          }
        },
        series: [
          {
            name: '人口涌入',
            type: 'bar',
            data: this.inflowData
          },
          {
            name: '人口流失',
            type: 'bar',
            data: this.outflowData
          }
        ]
      };
      this.chart.setOption(option);
    },
    updateChart() {
      // 模拟数据更新
      // map 会遍历 this.cities 数组中的每个城市。
      // Math.random() 生成一个 [0, 1) 之间的随机小数。
      // Math.floor(...) 对结果取整，
      this.inflowData = this.cities.map(() => Math.floor(Math.random() * 1000));
      this.outflowData = this.cities.map(() => Math.floor(Math.random() * 1000));
      // 更新图表
      this.chart.setOption({
        series: [
          { data: this.inflowData },
          { data: this.outflowData }
        ]
      });
    }
  }
};
</script>

<style scoped>
.left-bottom {
  width: 400px;
  margin-left: 80px;
  padding: 20px 20px;
  color: #fff;
}

.header {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: space-between;
  margin-top: 20px;
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 10px;
  margin-left: 10px;
  /* 与日期选择器的间距 */
}

.chart-container {
  width: 400px;
  height: 250px;
}
</style>